<template>
    <el-dialog
      v-model="dialogVisible"
      :title="getDialogTitle()"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
        class="dept-form"
      >
        <!-- 上级部门显示 -->
        <div class="form-row" v-if="parentDept.id">
          <el-form-item label="上级部门">
            <el-input
              :value="parentDept.deptName || '根部门'"
              disabled
              placeholder="根部门"
            />
          </el-form-item>
        </div>
  
        <!-- 部门名称 -->
        <div class="form-row">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="localFormData.deptName"
              placeholder="请输入部门名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </div>
  
        <!-- 负责人和联系电话 -->
        <div class="form-row">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-input
                  v-model="localFormData.leader"
                  placeholder="请输入负责人"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input
                  v-model="localFormData.phone"
                  placeholder="请输入联系电话"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
  
        <!-- 邮箱和排序 -->
        <div class="form-row">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="localFormData.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="localFormData.sort"
                  :min="0"
                  :max="999"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
  
        <!-- 状态 -->
        <div class="form-row">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="localFormData.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
  
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" :disabled="loading">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
          >
            {{ loading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, watch, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { deptApi } from '@/api/dept'
  
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    parentDept: {
      type: Object,
      default: () => ({})
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'success'])
  
  // 响应式数据
  const dialogVisible = ref(false)
  const loading = ref(false)
  const formRef = ref()
  
  // 默认表单数据
  const defaultFormData = {
    parentId: 0,
    deptName: '',
    leader: '',
    phone: '',
    email: '',
    sort: 0,
    status: 1
  }
  
  // 本地表单数据
  const localFormData = ref({ ...defaultFormData })
  
  // 表单验证规则
  const formRules = {
    deptName: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
      { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    leader: [
      { max: 20, message: '负责人姓名不能超过20个字符', trigger: 'blur' }
    ],
    phone: [
      {
        pattern: /^1[3-9]\d{9}$|^(0\d{2,3}-?)?\d{7,8}$/,
        message: '请输入正确的联系电话',
        trigger: 'blur'
      }
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: 'blur'
      }
    ],
    sort: [
      { required: true, message: '请输入排序号', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
  }
  
  // 获取对话框标题
  const getDialogTitle = () => {
    if (props.isEdit) {
      return '编辑部门'
    } else if (props.parentDept.id) {
      return `新增子部门 - ${props.parentDept.deptName}`
    } else {
      return '新增部门'
    }
  }
  
  // 监听props变化
  watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
    if (val) {
      nextTick(() => {
        resetForm()
        initializeFormData()
      })
    }
  })
  
  // 监听dialogVisible变化
  watch(dialogVisible, (val) => {
    emit('update:modelValue', val)
  })
  
  // 初始化表单数据
  const initializeFormData = () => {
    if (props.isEdit && props.formData) {
      // 编辑模式：使用传入的数据
      const formData = {
        ...defaultFormData,
        ...props.formData
      }
      localFormData.value = { ...formData }
    } else {
      // 新增模式：重置为默认值
      localFormData.value = { ...defaultFormData }
      // 设置父部门ID
      if (props.parentDept.id) {
        localFormData.value.parentId = props.parentDept.id
      }
    }
  }
  
  // 重置表单验证
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
  
  // 关闭对话框
  const handleClose = () => {
    if (loading.value) {
      ElMessage.warning('正在提交，请稍候...')
      return
    }
    
    dialogVisible.value = false
    // 延迟重置表单，避免动画卡顿
    setTimeout(() => {
      localFormData.value = { ...defaultFormData }
    }, 300)
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) {
      ElMessage.error('表单引用不存在')
      return
    }
  
    try {
      // 表单验证
      const valid = await formRef.value.validate()
      if (!valid) {
        return
      }
  
      loading.value = true
  
      // 准备提交数据
      const submitData = { ...localFormData.value }
  
      let response
      if (props.isEdit) {
        response = await deptApi.updateDept(submitData)
      } else {
        response = await deptApi.addDept(submitData)
      }
  
      // 判断响应结果
      if (response.code === 1) {
        ElMessage.success(props.isEdit ? '更新部门成功' : '新增部门成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      if (error.errors) {
        // 表单验证错误，Element Plus 会自动显示错误信息
        return
      }
      
      // 网络错误或其他异常
      if (error.response) {
        ElMessage.error(`服务器错误: ${error.response.data?.msg || error.response.status}`)
      } else if (error.request) {
        ElMessage.error('网络错误，请检查网络连接')
      } else {
        ElMessage.error('操作失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  }
  
  // 暴露方法给父组件
  defineExpose({
    resetForm,
    handleClose
  })
  </script>
  
  <style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }
  
  /* 表单间距调整 */
  :deep(.dept-form) {
    padding: 10px 0;
  }
  
  .form-row {
    margin-bottom: 24px;
  }
  
  .form-row:last-child {
    margin-bottom: 0;
  }
  
  :deep(.dept-form .el-form-item) {
    margin-bottom: 0;
  }
  
  :deep(.dept-form .el-form-item__label) {
    font-weight: 500;
    padding-right: 10px;
    color: #606266;
  }
  
  :deep(.dept-form .el-input) {
    width: 100%;
  }
  
  :deep(.dept-form .el-radio-group) {
    display: flex;
    gap: 20px;
  }
  
  :deep(.dept-form .el-select) {
    width: 100%;
  }
  
  :deep(.dept-form .el-input-number) {
    width: 100%;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px 25px;
  }
  </style>